<template>
    <div class="change-password-box">

        <el-form ref="dataFormRef" label-width="110px" :model="dataForm" :rules="rules">
            <el-form-item label="旧密码" prop="sourcePassword">
                <el-input v-model="dataForm.sourcePassword" style="width: 420px" placeholder="请输入旧密码"
                    :show-password="!showPassword" :readonly="passwordReadonly['sourcePassword']"
                    @focus="setReadonly('sourcePassword')" @blur="setReadonly('sourcePassword')" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="dataForm.newPassword" style="width: 420px" placeholder="请输入6-20位密码，包含数字、大小写字母和符号至少两种组合"
                    :show-password="!showPassword" :readonly="passwordReadonly['newPassword']"
                    @focus="setReadonly('newPassword')" @blur="setReadonly('newPassword')" />
            </el-form-item>
            <el-form-item label="确认新密码" prop="newPasswordAgain">
                <el-input v-model="dataForm.newPasswordAgain" style="width: 420px" placeholder="请再次输入新密码"
                    :show-password="!showPassword" :readonly="passwordReadonly['newPasswordAgain']"
                    @focus="setReadonly('newPasswordAgain')" @blur="setReadonly('newPasswordAgain')" />
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="showPassword" label="显示密码" />
            </el-form-item>
        </el-form>
        <div class="btngroup">
            <el-button type="primary" @click="closedHandle">取消</el-button>
            <el-button type="success" @click="confirmHandle">确定</el-button>
        </div>

    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { modifyPassword } from '@/api/auth';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/modules/user';
import { ElMessage } from 'element-plus';
import emits from '@/utils/emits';
const userStore = useUserStore()
const router = useRouter();
const dataFormRef = ref()
const showPassword = ref(false)

const passwordReadonly = reactive<any>({
    sourcePassword: true,
    newPassword: true,
    newPasswordAgain: true
})
const dataForm = reactive({
    sourcePassword: '',
    newPassword: '',
    newPasswordAgain: ''
})

const validatePassword = (rule: any, value: any, callback: any) => {
    const passwordReg =
        /(?!^[0-9]+$)(?!^[a-z]+$)(?!^[A-Z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{6,20}$/

    if (!value) {
        return callback(new Error('请输入新密码'))
    } else if (value.length < 6) {
        return callback(new Error('请输入至少6位新密码'))
    } else if (!passwordReg.test(value)) {
        return callback(new Error('请输入6-20位密码，包含数字、大小写字母和符号至少两种组合'))
    } else {
        callback()
    }
}


const validateNwPassword = (rule: any, value: any, callback: any) => {
    const passwordReg =
        /(?!^[0-9]+$)(?!^[a-z]+$)(?!^[A-Z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{6,20}$/

    if (!value) {
        return callback(new Error('请再次输入新密码'))
    } else if (value.length < 6) {
        return callback(new Error('请输入至少6位新密码'))
    } else if (value !== dataForm.newPassword) {
        return callback(new Error('两次输入的新密码不一致'))
    } else if (!passwordReg.test(value)) {
        return callback(new Error('请输入6-20位密码，包含数字、大小写字母和符号至少两种组合'))
    } else {
        callback()
    }
}

const rules = reactive({
    sourcePassword: { required: true, trigger: 'blur', message: '请输入旧密码' },
    newPassword: { required: true, trigger: 'blur', validator: validatePassword },
    newPasswordAgain: { required: true, trigger: 'blur', validator: validateNwPassword }
});

const confirmHandle = () => {

    dataFormRef.value.validate((valid: boolean) => {
        if (valid) {


      

            modifyPassword({
                userId: userStore.user.id,
                sourcePassword: window.btoa(dataForm.sourcePassword),
                newPassword: window.btoa(dataForm.newPassword),
                newPasswordAgain: window.btoa(dataForm.newPasswordAgain)
            })
                .then(({ data }) => {
                    console.log(data)
                    if (data) {
                        ElMessage.success('修改密码成功，即将跳转重新登录')
                        setTimeout(() => {
                            userStore.logoutAction().then(() => {
                                router.replace('/login')
                            })
                        }, 1000)

                    }
                })
                .finally(() => {
                })
        }
    })
};

const closedHandle = () => {
    // 重置表单数据
    if (dataFormRef.value) {
        dataFormRef.value.resetFields()
    }
};

const setReadonly = (key: string) => {
    setTimeout(() => {
        passwordReadonly[key] = !passwordReadonly[key]
    })
};

onUnmounted(() => {
    emits.off('closeLoginBox')
})
onMounted(() => {
    emits.on('closeLoginBox', res => {
        if (res == false) {
            closedHandle()
        }
    })
})

</script>


<style scoped lang="scss">
.change-password-box {
    width: 100%;


    .avatar-container {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        height: var(--theme-header-height);

        .avatar-wrapper {
            display: flex;
            align-items: center;
            white-space: nowrap;
            padding-right: 15px;
            color: var(--theme-header-text-color);
        }


        :deep(.el-dropdown__popper) {
            width: 120px;

            .version {
                height: 32px;
                line-height: 32px;
                text-align: center;
                color: var(--theme-text-color-info);
                border-bottom: 1px solid var(--el-border-color-lighter);
            }
        }
    }


    :deep(.el-input__wrapper) {
        background-color: rgba(27, 68, 148, 0.46) !important;
        border: 0 !important;
    }

    :deep(.el-input__inner) {
        color: white !important;
        border: 0 !important;
    }

    :deep(.el-input) {
        color: black !important;
        border: 0 !important;

        .el-input__password {
            display: none;
        }
    }


    .btngroup {
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }
}
</style>